package org.association.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.association.bo.UserEntityExpandBO;
import org.association.entity.UserEntity;
import org.association.service.OrganizationService;
import org.association.service.UserService;
import org.association.util.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Api(tags = "用户登录接口")
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;


    @ApiOperation(value = "用户注册，不存在则创建，否则就是登录")
    @ApiImplicitParams( value = {
            @ApiImplicitParam(name = "privateKey", value = "私钥", dataTypeClass = UserEntity.class, required = true)
    })
    @PostMapping("/login/{privateKey}")
    public R login(@PathVariable String privateKey) {

        if(StringUtils.isEmpty(privateKey)) {
            return R.error().message("地址不能为空");
        }

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("private_key", privateKey);
        UserEntity entity = userService.getOne(queryWrapper);

        UserEntityExpandBO userEntityExpandBO = new UserEntityExpandBO();

        // 用户已存在，直接返回
        if(entity != null) {
            BeanUtils.copyProperties(entity, userEntityExpandBO);
            boolean enterOrganization = organizationService.userOrgExist(entity.getPrivateKey());
            if(!enterOrganization) {
                userEntityExpandBO.setAddedOrganization(false);
            } else {
                Integer orgId = organizationService.getOrgIdByPrimaryKey(privateKey);
                userEntityExpandBO.setOrganizationId(orgId);
                userEntityExpandBO.setAddedOrganization(true);
            }
            return R.ok().put("user", userEntityExpandBO);
        }

        // 设置地址
        UserEntity userEntity = new UserEntity();
        userEntity.setPrivateKey(privateKey);
        String address = userService.addUser(userEntity);

        userEntityExpandBO.setAddedOrganization(false); // 新用户都是没加协会的
        userEntityExpandBO.setAddress(address);
        userEntityExpandBO.setPrivateKey(privateKey);

        return R.ok().put("user", userEntityExpandBO);
    }
}
